import React from 'react'
import { AlertTriangle, RefreshCw } from 'lucide-react'
import { ErrorBoundary } from './ErrorBoundary'
import { Button } from './ui/Button'
import { Card, CardContent, CardHeader, CardTitle } from './ui/Card'

interface PluginErrorBoundaryProps {
  children: React.ReactNode
  pluginName: string
  onReload?: () => void
}

export function PluginErrorBoundary({ 
  children, 
  pluginName, 
  onReload 
}: PluginErrorBoundaryProps) {
  const handlePluginError = (error: Error) => {
    console.error(`Plugin ${pluginName} crashed:`, error)
    
    // 通知主应用插件崩溃
    window.dispatchEvent(new CustomEvent('plugin:error', {
      detail: { pluginName, error: error.message }
    }))
  }

  const fallback = (
    <Card className="border-destructive">
      <CardHeader>
        <div className="flex items-center space-x-2">
          <AlertTriangle className="w-5 h-5 text-destructive" />
          <CardTitle className="text-destructive">Plugin Error</CardTitle>
        </div>
      </CardHeader>
      <CardContent>
        <p className="text-sm text-muted-foreground mb-4">
          The plugin "{pluginName}" encountered an error and stopped working.
        </p>
        {onReload && (
          <Button onClick={onReload} size="sm">
            <RefreshCw className="w-4 h-4 mr-2" />
            Reload Plugin
          </Button>
        )}
      </CardContent>
    </Card>
  )

  return (
    <ErrorBoundary fallback={fallback} onError={handlePluginError}>
      {children}
    </ErrorBoundary>
  )
}
